﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;

namespace ToyundaPhone.Pages
{
	public partial class SongSearchPage : PhoneApplicationPage, System.ComponentModel.INotifyPropertyChanged
	{
		private Helpers.SongEnumHelper songEnumHelper;

		public SongSearchPage()
		{
			InitializeComponent();
			songEnumHelper = new Helpers.SongEnumHelper(e => Dispatcher.BeginInvoke(() => OnPropertyChanged("Songs")), songList);
		}

		private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
		{
			string IdParam = NavigationContext.QueryString["playlist"];
			int id;
			if (!int.TryParse(IdParam, out id))
			{
				NavigationService.GoBack();
				return;
			}
			Database.SongDatabase db = (Application.Current as App).SongDatabase;
			Database.Playlist pl = (from p in db.Playlists where p.Id == id select p).FirstOrDefault();
			if (pl == null)
			{
				NavigationService.GoBack();
				return;
			}
			Playlist = pl;
			OnPropertyChanged("Playlist");
			if (Songs == null)
			{
				songList.EmptyText = "Chargement en cours…";
				Songs = songEnumHelper.GetEnumerator(from s in (Application.Current as App).SongDatabase.Songs orderby s.Work, s.Title select s);
				songEnumHelper.NotifyUpdate();
			}
		}

		private void Search_TextChanged(object sender, EventArgs e)
		{
			var predicate = ToyundaPhone.Helpers.PredicateBuilder.True<ToyundaPhone.Database.Song>();
			foreach (var keyword in (Application.Current as App).SongDatabase.WordExtractor.GetWords(Search.Text).Select(w => " " + w))
			{
				var tmpKeyword = keyword;
				predicate = ToyundaPhone.Helpers.PredicateBuilder.And(predicate, s => s.SearchText.Contains(tmpKeyword));
			}
			songList.EmptyText = "Chargement en cours…";
			Songs = songEnumHelper.GetEnumerator((Application.Current as App).SongDatabase.Songs.Where(predicate).OrderBy(s => s.Work).ThenBy(s => s.Title));
			songEnumHelper.NotifyUpdate();
		}

		#region INotifyPropertyChanged Members

		public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

		#endregion

		public Database.Playlist Playlist { get; private set; }
		public IEnumerable<ToyundaPhone.Database.Song> Songs { get; private set; }

		private void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
			}
		}

		private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
		{
			Microsoft.Phone.Shell.SystemTray.SetIsVisible(this, e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitUp || e.Orientation == PageOrientation.PortraitDown);
		}
	}
}